<?php
/**
 *
 * User:xinhuazhang
 * Date:2024/5/20
 * TIPS:功能说明
 * Email:<1655626823@qq.com>
 */

namespace app\api\controller;

use app\admin\model\Houses as HousesModel;
use app\admin\model\member\Rights;
use app\admin\model\User;
use app\common\controller\Frontend;
use app\common\library\xmwechat\offiaccount\OaService;
use app\common\library\xmwechat\payment\PayService;
use app\common\model\imchat\Message;
use app\common\model\Wxinfo;
use Symfony\Component\HttpClient\Exception\ClientException;
use Symfony\Component\HttpClient\Exception\ServerException;
use think\Exception;
use think\facade\Db;

#[Apidoc\Title("订单管理")]
class Orders extends Frontend
{
    protected array $noNeedPermission = ["*"];
    protected array $noNeedLogin=['refund2'];

    public function index()
    {

    }

    #[
        Apidoc\Title("支付悬赏金额"),
        Apidoc\Desc("支付悬赏金额"),
        Apidoc\Url("api/orders/payment"),
        Apidoc\Method("POST"),
        Apidoc\Param("id", type: "string", require: "true", desc: "店id", mock: "2"),
        //Apidoc\Param("to_uid", type: "int", require: "true", desc: "查找的用户id", mock: "2"),
        Apidoc\Param("type", type: "string", require: "true", desc: "默认houses, 类型 房源houses, 找店findstore", mock: "houses"),
        Apidoc\Return("json", "返回支付信息", [
            ["payment", "支付信息", "json", '{
			"appId": "wx2b1b3222bf4cab2b",
			"timeStamp": "1716708954",
			"nonceStr": "SJrCu8L7aYeOHgcF",
			"package": "prepay_id=wx2615360304115267a82a63e9184a2f0000",
			"signType": "RSA",
			"paySign": "OgC8mMTVnm60NC7KqzSPaCuHTjg1wofEjg0GphtyB1DlIbAgR/g9Nw0KiVBt9xuOqMxjF0QzXQAOwGcYDQHPMzkyAOlLBf6qpAVCnKyBb6SZR4mgVRUFiLrWJnj2KnI0n1+zWx3iRJO0xhuyJFP3SSiRBZzzS5VMkFMM6ZMltIka3TfpO6Uhov4+mgYrqvZZhHpTwDrWQfxT3+NOz7qK8i4WPvfayGlsFRHhxpz2rpDWPjDmAxENpxKe7UY/RZhcoanUtiQ4GWSTUAtsWxzyp+ukIPPOUWHLwsb4kOIhAFW0cbGpZNBvToNrAkNyKH2isl1u2RxtnnaArMYFv/XFMQ=="
		}'],
            ["order_no", "订单号", "string", ""]
        ])
    ]
    public function payment()
    {
        $id = $this->request->post("id");
        $to_uid = $this->request->post("to_uid");
        if (empty($to_uid)) {
            // $this->error("请选择用户");
        }
        $type = $this->request->post("type", 'houses');
        if (!in_array($type, ['houses', 'findstore'])) {
            $this->error("参数错误");
        }
        if ($type == 'houses') {
            $houses = \app\admin\model\Houses::where('id', $id)->find();
            if (!$houses) {
                $this->error("房源不存在");
            }
            $order_amount = $houses['reward'];
        } else if ($type == 'findstore') {
            $findstore = \app\common\model\Findstore::where('id', $id)->find();
            if (!$findstore) {
                $this->error("找店不存在");
            }
            $order_amount = $findstore['reward'];
        }
        $order_data = [
            'order_no' => date("YmdHis") . rand(1000, 9999),
            'order_amount' => $order_amount,
            'pay_status' => 0,
            'user_id' => $this->auth->id,
            'to_uid' => $to_uid,
            'house_id' => $id,
            'house_type' => $type,
            'create_time' => time(),
            'update_time' => time(),
        ];
        Db::startTrans();
        $result = (new \app\common\model\Orders())->save($order_data);
        // order_no:订单号，body:描述，pay_price:支付金额， openid：当前用户openid
        try {
            $payment = PayService::getInstance()->pay([
                'order_no' => $order_data['order_no'],
                'transaction_no' => $order_data['order_no'],
                'body' => '佣金支付' . $order_data['order_no'],
                'pay_price' => $order_amount,
                'openid' => $this->auth->mini_openid,
                'pay_type' => 'miniProgram'
            ]);
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        if ($result) {
            Db::commit();
            $this->success("返回支付信息", ['payment' => $payment, 'order_no' => $order_data['order_no']]);
        } else {
            Db::rollback();
            $this->error("生成支付信息支付");
        }
    }

    #[
        Apidoc\Title("退款"),
        Apidoc\Desc(" 退款说明：下架房源25个工作日后才可以退款，退款金额原路返回。.房源详情的pay_status 1为已支付，2为未支付，3为已退款 payed_day为支付天数"),
        Apidoc\Method("POST"),
        Apidoc\Url("/api/orders/refund"),
        Apidoc\Param(name: "id", type: "id", require: true, desc: "房源id", mock: "1"),

        Apidoc\Param("type", type: "string", require: "true", desc: "默认houses, 类型 房源houses, 找店findstore", mock: "houses"),
        Apidoc\Returned("id", type: "int", desc: "Id"),
    ]
    public function refund()
    {
        try {
            $id = $this->request->param("id");

            $type = $this->request->post("type", 'houses');
            if (!in_array($type, ['houses', 'findstore'])) {
                $this->error("参数错误");
            }
            if ($type == 'houses') {

                $result = HousesModel::where(['id' => $id, 'user_id' => $this->auth->id])->find();
                if (!$result) {
                    $this->error("房源不存在");
                }
            } else {
                $result = \app\common\model\Findstore::where(['id' => $id, 'user_id' => $this->auth->id])->find();
                if (!$result) {
                    $this->error("找店不存在");
                }
            }
            $order_row = (new \app\common\model\Orders())->where([
                'house_id' => $id,
                'house_type' => 'houses',
                'pay_status' => 1,
                'user_id' => $this->auth->id
            ])->order('id desc')->find();
            if (!$order_row) {
                $this->error("找不到订单支付数据");
            }
            $payed_day = (time() - $order_row['paid_time']) / (3600 * 24);
            if ($payed_day < 25) {
                $this->error("退款失败，上架25个工作日才可以退款");
            }
            $refund_result = PayService::getInstance()->refunds([
                'out_trade_no' => $order_row['order_no'],
                'transaction_id' => $order_row['transaction_id'],
                'reason' => '下架房源',
                'refund_price' => $order_row['order_amount'],
                'pay_price' => $order_row['order_amount'],
            ]);
            $order_row->save(['pay_status' => 2, 'update_time' => time()]);
            $result->save(['status' => 0, 'order_id' => 0, 'update_time' => time(), 'down_time' => time()]);
            $this->success('退款成功，金额原路返回', $refund_result);
        } catch (Exception $e) {
            $this->error("退款失败");
        }
    }

    #[
        Apidoc\Title("房源详情 或者 找店详情 里面支付佣金"),
        Apidoc\Desc("将支付的悬赏佣金支付出去"),
        Apidoc\Url("api/orders/drawpay"),
        Apidoc\Method("POST"),
        Apidoc\Param("id", type: "string", require: "true", desc: "详情idid", mock: "2"),
        Apidoc\Param("type", type: "string", require: "true", desc: "默认houses, 类型 房源houses, 找店findstore", mock: "houses"),
        Apidoc\Return("json", "返回支付信息", [
            ["payment", "支付信息", "json", '{
			"appId": "wx2b1b3222bf4cab2b",
			"timeStamp": "1716708954",
			"nonceStr": "SJrCu8L7aYeOHgcF",
			"package": "prepay_id=wx2615360304115267a82a63e9184a2f0000",
			"signType": "RSA",
			"paySign": "OgC8mMTVnm60NC7KqzSPaCuHTjg1wofEjg0GphtyB1DlIbAgR/g9Nw0KiVBt9xuOqMxjF0QzXQAOwGcYDQHPMzkyAOlLBf6qpAVCnKyBb6SZR4mgVRUFiLrWJnj2KnI0n1+zWx3iRJO0xhuyJFP3SSiRBZzzS5VMkFMM6ZMltIka3TfpO6Uhov4+mgYrqvZZhHpTwDrWQfxT3+NOz7qK8i4WPvfayGlsFRHhxpz2rpDWPjDmAxENpxKe7UY/RZhcoanUtiQ4GWSTUAtsWxzyp+ukIPPOUWHLwsb4kOIhAFW0cbGpZNBvToNrAkNyKH2isl1u2RxtnnaArMYFv/XFMQ=="
		}'],
            ["order_no", "订单号", "string", ""]
        ])
    ]
    public function drawpay()
    {
        $id = $this->request->param("id");
        $to_uid = $this->request->param("to_uid");
        $type = $this->request->param("type");
        $type = $this->request->post("type", 'houses');
        if (!in_array($type, ['houses', 'findstore'])) {
            $this->error("参数错误");
        }
        if ($type == 'houses') {
            $result = HousesModel::where(['id' => $id, 'user_id' => $this->auth->id])->find();

            if (!$result) {
                $this->error("房源不存在");
            }
        } else if ($type == 'findstore') {
            $findstore = \app\common\model\Findstore::where('id', $id)->find();
            if (!$findstore) {
                $this->error("找店不存在");
            }
        }
        $order = (new \app\admin\model\Orders())->where([
            'user_id' => $this->auth->id,
            // 'to_uid' => $to_uid,
            'house_id' => $id,
            'house_type' => $type])
            ->find();
        if (!$order) {
            $this->error("未支付过佣金");
        }
        if ($order['pay_status'] != 1) {
            $this->error("未支付过佣金");
        }
        if ($type == 'houses') {
            $result->save(['status' => 4]);
        } else {
            $findstore->save(['status' => 4]);
        }

        $order->save(['to_uid' => $to_uid, 'pay_status' => 3, 'update_time' => time()]);

        try {
            $check = '您有新的赏金到账，请前往个人中心查看。';
            $ret = Message::insertMsg(['content' => $check, 'type' => 0, 'to_uid' =>$to_uid, 'from_uid' => 10], 10);
            $unionid = (new User())->where('id', '=',$to_uid)->value('weixin_unionid');
            $openid = (new Wxinfo())->where(['unionid' => $unionid])->value('wxopenid');// 'oyMrVspaMfT-QfD0qjaU7W-_1tBU';
            if ($openid) {
                $template_id = '10dAODMpbdJIXUt0oiNt7USIs6qYg3K5cgOwdKx_o-E';
                $data = [
                    'thing1' => ['value' => '您有新的赏金到账', 'color' => '#888888'],
                    'character_string5' => ['value' => $order['order_no'], 'color' => '#888888'],
                    'const2' => ['value' =>'待提现', 'color' => '#888888'],
                    'character_string1' => ['value' => time() . rand(999999, 1000000), 'color' => '#888888'],
                ];
                /*详细内容

工单名称
{{thing1.DATA}}
订单编号
{{character_string5.DATA}}
当前工单进度
{{const2.DATA}}
管理枚举值
跳转文案
点击查看详情
管理文案*/
                // 模板跳转链接,不跳转可忽略此参数
                $url = '';
                // 跳小程序所需数据,不需跳小程序可不用传该数据，小程序appid必须已绑定关联当前公众号
                $miniprogram = [
                    'appid' => 'wx2b1b3222bf4cab2b',
                    'pagepath' => 'pages/home/index'
                ];
                (new OaService())->sendTemplateMessage($openid, $template_id, $data, $url, $miniprogram);
            }
        } catch (\ba\Exception $exception) {

        }
        $this->success('佣金已付出');
    }

    public function refund2()
    {
        $id = $this->request->post('id/d');
        $id=181;
        $order_row = (new \app\common\model\Orders())->where(['id' => $id])->find();
        $refund_result = PayService::getInstance()
            ->refunds([
                'out_trade_no' => $order_row['order_no'],
                'transaction_id' => $order_row['transaction_id'],
                'reason' => '下架房源',
                'refund_price' => $order_row['order_amount'],
                'pay_price' => $order_row['order_amount'],
            ]);
        $order_row->save(['pay_status' => 2, 'update_time' => time()]);
        $type=$order_row['house_type'];
        if ($type == 'houses') {
            $result = HousesModel::where(['id' => $id, 'user_id' => $this->auth->id])->find();
            if (!$result) {
                $this->error("房源不存在");
            }
        } else {
            $result = \app\common\model\Findstore::where(['id' => $id, 'user_id' => $this->auth->id])->find();
            if (!$result) {
                $this->error("找店不存在");
            }
        }
        $result->save(['status' => 0, 'order_id' => 0, 'update_time' => time(), 'down_time' => time()]);
        $this->success();
    }

    /**
     * 支付看房佣金
    */
    #[
        Apidoc\Title("支付看房佣金 版本3.0
        会员权益开通传值成为vip
        "),
        Apidoc\Desc("'houses 看房', 'findstore 找店','isvip 成为vip'"),
        Apidoc\Url("api/orders/drawpay"),
        Apidoc\Method("POST"),
        Apidoc\Param("id", type: "string", require: "true", desc: "详情id对应房源id   找店id  以及成为vip id不同类型值不同", mock: "2"),
        Apidoc\Param("type", type: "string", require: "true", desc: "houses 看房', 'findstore 找店','isvip 成为vip", mock: "houses"),
        Apidoc\Return("json", "返回支付信息", [
            ["payment", "支付信息", "json", '{
			"appId": "wx2b1b3222bf4cab2b",
			"timeStamp": "1716708954",
			"nonceStr": "SJrCu8L7aYeOHgcF",
			"package": "prepay_id=wx2615360304115267a82a63e9184a2f0000",
			"signType": "RSA",
			"paySign": "OgC8mMTVnm60NC7KqzSPaCuHTjg1wofEjg0GphtyB1DlIbAgR/g9Nw0KiVBt9xuOqMxjF0QzXQAOwGcYDQHPMzkyAOlLBf6qpAVCnKyBb6SZR4mgVRUFiLrWJnj2KnI0n1+zWx3iRJO0xhuyJFP3SSiRBZzzS5VMkFMM6ZMltIka3TfpO6Uhov4+mgYrqvZZhHpTwDrWQfxT3+NOz7qK8i4WPvfayGlsFRHhxpz2rpDWPjDmAxENpxKe7UY/RZhcoanUtiQ4GWSTUAtsWxzyp+ukIPPOUWHLwsb4kOIhAFW0cbGpZNBvToNrAkNyKH2isl1u2RxtnnaArMYFv/XFMQ=="
		}'],
            ["order_no", "订单号", "string", ""]
        ])
    ]
    public function payrights()
    {
        $id = $this->request->post("id");
        $to_uid = $this->request->post("to_uid");
        if (empty($to_uid)) {
            // $this->error("请选择用户");
        }
        $type = $this->request->post("type", 'houses');
        if (!in_array($type, ['houses', 'findstore','isvip','oneview'])) {
            $this->error("参数错误");
        }
        if ($type == 'houses') {
            $houses = \app\admin\model\Houses::where('id', $id)->find();
            if (!$houses) {
                $this->error("房源不存在");
            }
            $to_uid=$houses['user_id'];
            $order_amount = $houses['view_price'];
        } else if ($type == 'findstore') {
            $findstore = \app\common\model\Findstore::where('id', $id)->find();
            if (!$findstore) {
                $this->error("找店不存在");
            }
            $to_uid=$findstore['user_id'];
            $order_amount = $findstore['view_price'];
        } else if ($type == 'isvip') {
            $rights=(new Rights())->where('id', $id)->find();
            if(!!$rights){
                $this->error('找不到权益');
            }
            $order_amount = $rights['current_price'];
        }else if($type == 'oneview'){
            //c错付 单词看房数据是从房源看的
            $order_amount =10;// TODO 看一次房多钱
        }
        $order_data = [
            'order_no' =>'vip'. date("YmdHis") . rand(1000, 9999),
            'order_amount' => $order_amount,
            'pay_status' => 0,
            'user_id' => $this->auth->id,
            'to_uid' => $to_uid,
            'house_id' => $id,
            'version'=>2,
            'house_type' => $type,
            'create_time' => time(),
            'update_time' => time(),
            'order_type' => $type,
        ];
        Db::startTrans();
        $result = (new \app\common\model\Orders())->save($order_data);
        // order_no:订单号，body:描述，pay_price:支付金额， openid：当前用户openid
        try {
            $payment = PayService::getInstance()->pay([
                'order_no' => $order_data['order_no'],
                'transaction_no' => $order_data['order_no'],
                'body' => '新版本订单' . $order_data['order_no'],
                'pay_price' => $order_amount,
                'openid' => $this->auth->mini_openid,
                'pay_type' => 'miniProgram'
            ]);
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result) {
            Db::commit();
            $this->success("返回支付信息", ['payment' => $payment, 'order_no' => $order_data['order_no']]);
        } else {
            Db::rollback();
            $this->error("生成支付信息支付");
        }
    }
}
